<script setup>

import { useUserStore } from '@/store/index.js'
import { PostBindEmail, PostSendEmailCode, PostUnBindEmail } from '@/apis/user'
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Message } from '@element-plus/icons-vue'

const userStore = useUserStore()

//邮箱账户是否可修改
const isemailEdit = ref(!userStore.userInfo.email)

//发送按钮是否可以点击
const isclikSend = ref(true)

//发送验证码按钮切换
const sendemailbutton = ref({
  message: '发送验证码',
  count: 60
})

//存一份用户数据
const userinfo = ref({})
//

//表单检验
const emailformref = ref(null)
const emailform = ref({
  code: ''
})

const rules = {
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},

  ],
  email: [
    {required: true, message: '请输入邮箱账号'},
  ],

}


onMounted(() => {
  //浅拷贝一份 防止污染pinia的数据
  userinfo.value = {...userStore.userInfo}
  emailform.value.username = userinfo.value.username
  emailform.value.email = userinfo.value.email
})

//发送邮箱验证码
const onSendemail = async () => {

  if (emailform.value.email != null) {
    //校验验证码格式
    const emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
    if (!emailReg.test(emailform.value.email)) {
      ElMessage({type: 'warning', message: "请输入正确的邮箱地址"})
      return;
    }
    isclikSend.value = !isclikSend.value
    sendemailbutton.value.message = `${ sendemailbutton.value.count }秒后再试`
    const timer = setInterval(() => {
      sendemailbutton.value.count--
      sendemailbutton.value.message = `${ sendemailbutton.value.count }秒后再试`
      if (sendemailbutton.value.count < 0) {
        isclikSend.value = !isclikSend.value
        sendemailbutton.value.message = '发送验证码'
        window.clearInterval(timer);
      }
    }, 1000);
    await PostSendEmailCode(emailform.value)
  } else {
    ElMessage({type: 'warning', message: "请填写邮箱"})
  }


}


//绑定邮箱
const onBindemail = () => {
  emailformref.value.validate(async (valid) => {
    if (valid) {
      const res = await PostBindEmail(emailform.value)
      if (res.code == 200) {
        alert("绑定成功")
        isemailEdit.value = !isemailEdit.value
        userStore.bindemail(emailform.value.email)
      }
    } else {
      console.log('error submit!!');
      return false;
    }
  })
}
//解除绑定
const updatemail = async () => {
  ElMessageBox.confirm(
      '你确定要取消绑定邮箱吗',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        icon: Message,
        center: true,
      }
  )
      .then(async () => {
        const res = await PostUnBindEmail(userinfo.value)
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '解绑成功',
          })
          emailform.value.code = ''
          isemailEdit.value = !isemailEdit.value
          userStore.unbindemail()
        }

      })
      .catch(() => {

      })


}

</script>

<template>
  <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 24px">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>个人邮箱绑定</el-breadcrumb-item>
  </el-breadcrumb>

  <el-form :model="emailform" :rules="rules" ref='emailformref' class="demo-form-inline" label-width=auto
           label-position='center'>

    <el-form-item label="用户名">
      <el-input disabled clearable v-model=emailform.username />
    </el-form-item>

    <el-form-item label="邮箱账号" prop="email">

      <el-input :disabled="!isemailEdit" label-position='left' clearable v-model=emailform.email />
      <el-form-item>

        <el-button type="success" @click="onSendemail" :disabled="!isclikSend" v-if=!userStore.userInfo.email>{{
            sendemailbutton.message
          }}
        </el-button>

      </el-form-item>


    </el-form-item>


    <el-form-item v-if=!userStore.userInfo.email label="邮箱验证码" prop="code">

      <el-input label-position='left' clearable v-model=emailform.code />

      <el-button type="success" @click="onBindemail()" v-if=!userStore.userInfo.email>绑定</el-button>
    </el-form-item>


    <el-form-item label="状态">
      <el-button disabled type="primary" @click="onSubmit">{{
          userStore.userInfo.email ? '已绑定' : '未绑定'
        }}
      </el-button>
      <el-button type="success" @click="updatemail" v-if=userStore.userInfo.email>取消绑定</el-button>
    </el-form-item>


  </el-form>
</template>

<style lang="less" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;

}

//第一个button有效
.el-button {
  margin-left: 30px
}


</style>
